package com.fengye.rabbit.login.message;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengye.rabbit.login.dto.UserLoginDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 *
 * @author sky
 * @date 2021年06月09日 3:43 下午
 */
@Component
@Slf4j
public class LoginPublisher {


    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    ObjectMapper objectMapper;

    @Value("${login.message.exchange.name:login-exchange-name}")
    private String exchangeName;

    @Value("${login.message.route.name:login-route-name}")
    private String routeName;

    public void sendLogMsg(UserLoginDTO dto) {
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        rabbitTemplate.setExchange(exchangeName);
        rabbitTemplate.setRoutingKey(routeName);

        try {
            rabbitTemplate.convertAndSend(dto, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    MessageProperties messageProperties = message.getMessageProperties();
                    messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    messageProperties.setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, UserLoginDTO.class);

                    return message;
                }
            });

            log.info("登陆成功，发送消息，用户信息为：{}", dto);
        } catch (Exception e) {
            log.info("发送消息异常，用户信息为：{}", dto, e.fillInStackTrace());
        }
    }
}
